package com.cskaoyan.service.wx.cqw;

import com.cskaoyan.mapper.*;
import com.cskaoyan.module.bean.BaseRespVo;
import com.cskaoyan.module.bo.wx.cqw.WxGoodsListBO;
import com.cskaoyan.module.pojo.*;
import com.cskaoyan.module.vo.wx.cqw.*;
import com.cskaoyan.service.configmanage.MarketConfigService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WxHomeIndexImpl implements WxHomeIndexService {
    @Autowired
    MarketConfigService marketConfigService ;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketAdMapper marketAdMapper;
    @Autowired
    MarketTopicMapper marketTopicMapper;
    @Autowired
    MarketBrandMapper marketBrandMapper;
    @Autowired
    MarketGrouponMapper marketGrouponMapper;
    @Autowired
    MarketCategoryMapper marketCategoryMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    MarketCollectMapper marketCollectMapper;
    @Autowired
    MarketIssueMapper marketIssueMapper;
    @Autowired
    MarketGrouponRulesMapper marketGrouponRulesMapper;
    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;

    @Autowired
    MarketFootprintMapper footprintMapper;



    @Override
    public BaseRespVo getIndex() {


        WxHomeIndexVO2 wxHomeIndexVO2 = new WxHomeIndexVO2();
        //banner
        MarketAdExample marketAdExample = new MarketAdExample();
        marketAdExample.createCriteria().andEnabledEqualTo(true);
        List<MarketAd> marketAds = marketAdMapper.selectByExample(marketAdExample);
        wxHomeIndexVO2.setBanner(marketAds);
        //newGoodsList hotGoodsList
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andIsNewEqualTo(true);
        List<MarketGoods> newGoodsList = marketGoodsMapper.selectByExample(example);
        wxHomeIndexVO2.setNewGoodsList(newGoodsList);
        MarketGoodsExample example1 = new MarketGoodsExample();
        example1.createCriteria().andIsHotEqualTo(true);
        List<MarketGoods> hotGoodsList = marketGoodsMapper.selectByExample(example1);
        wxHomeIndexVO2.setHotGoodsList(hotGoodsList);
        //topicList
        MarketTopicExample marketTopicExample = new MarketTopicExample();
        marketTopicExample.createCriteria().andDeletedEqualTo(false);
        List<MarketTopic> topicList = marketTopicMapper.selectByExample(marketTopicExample);
        wxHomeIndexVO2.setTopicList(topicList);
        //brandList
        MarketBrandExample marketBrandExample = new MarketBrandExample();
        marketBrandExample.createCriteria().andDeletedEqualTo(false);
        List<MarketBrand> brandList = marketBrandMapper.selectByExample(marketBrandExample);
        wxHomeIndexVO2.setBrandList(brandList);
        //grouponList
        MarketGrouponExample marketGrouponExample = new MarketGrouponExample();
        marketGrouponExample.createCriteria().andDeletedEqualTo(false);
        List<MarketGroupon> grouponList = marketGrouponMapper.selectByExample(marketGrouponExample);
        wxHomeIndexVO2.setGrouponList(grouponList);
        //channel
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        marketCategoryExample.createCriteria().andPidEqualTo(0);
        List<MarketCategory> channel = marketCategoryMapper.selectByExample(marketCategoryExample);
        wxHomeIndexVO2.setChannel(channel);
//couponList"
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        marketCouponExample.createCriteria().andDeletedEqualTo(false);

        List<MarketCoupon> couponList = marketCouponMapper.selectByExample(marketCouponExample);
        wxHomeIndexVO2.setCouponList(couponList);
        //floorGoodsList
        ArrayList<WxHomeIndexVO2FloorGood> floorGoodsList = new ArrayList<>();
        for (MarketCategory marketCategory : channel) {
            WxHomeIndexVO2FloorGood floorGood = new WxHomeIndexVO2FloorGood();
            floorGood.setName(marketCategory.getName());
            floorGood.setId(marketCategory.getId());
            MarketGoodsExample goodsExample = new MarketGoodsExample();
            goodsExample.createCriteria().andCategoryIdEqualTo(marketCategory.getId());
            List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(goodsExample);
            floorGood.setGoodsList(marketGoods);
            floorGoodsList.add(floorGood);

        }
        wxHomeIndexVO2.setFloorGoodsList(floorGoodsList);


        return BaseRespVo.ok(wxHomeIndexVO2);
    }



    @Override
    public BaseRespVo getGoodsCount() {

        Long l = marketGoodsMapper.countByExample(null);

        return BaseRespVo.ok(l.intValue());
    }

    @Override
    public BaseRespVo getCategorylistByPid(Integer id) {
        WxGoodsCategoryVO wxGoodsCategoryVO = new WxGoodsCategoryVO();

        //currentCategory 传入id为id
        MarketCategoryExample currentCategoryMarketCategoryExample = new MarketCategoryExample();
        currentCategoryMarketCategoryExample.createCriteria().andIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketCategory> currentCategoryList = marketCategoryMapper.selectByExample(currentCategoryMarketCategoryExample);


        MarketCategory getCategory4id = currentCategoryList.get(0);


        if (getCategory4id.getLevel().equals("L1")) {
            //currentCategory 传入id为Pid
            MarketCategoryExample idAsPid = new MarketCategoryExample();
            idAsPid.createCriteria().andDeletedEqualTo(false).andPidEqualTo(id);
            List<MarketCategory> brotherCategories = marketCategoryMapper.selectByExample(idAsPid);
            wxGoodsCategoryVO.setBrotherCategory(brotherCategories);
            wxGoodsCategoryVO.setParentCategory(getCategory4id);
            wxGoodsCategoryVO.setCurrentCategory(brotherCategories.get(0));
        } else {
            Integer pid = getCategory4id.getPid();
            MarketCategoryExample idAsPid4L2 = new MarketCategoryExample();
            idAsPid4L2.createCriteria().andDeletedEqualTo(false).andPidEqualTo(pid);
            List<MarketCategory> brotherCategories = marketCategoryMapper.selectByExample(idAsPid4L2);
            wxGoodsCategoryVO.setBrotherCategory(brotherCategories);
            for (MarketCategory brotherCategory : brotherCategories) {
                Integer id1 = brotherCategory.getId();
                if (id1.intValue() == id) {
                    wxGoodsCategoryVO.setCurrentCategory(brotherCategory);
                    break;
                }
                //查父类pid当作id
                MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(pid);
                wxGoodsCategoryVO.setParentCategory(marketCategory);
            }
        }


        return BaseRespVo.ok(wxGoodsCategoryVO);
    }


    //wx/goods/list?categoryId=1008005&page=1&size=100
    @Override
    public BaseRespVo getGoodsList(WxGoodsListBO wxGoodsListBO) {
        WxGoodsListVO wxGoodsListVO = new WxGoodsListVO();
       Integer categoryId = wxGoodsListBO.getCategoryId();
        Integer page = wxGoodsListBO.getPage();
        //  Integer limit = wxGoodsListBO.getLimit();

        //todo
        Integer limit = wxGoodsListBO.getLimit();


        List<MarketCategory> marketCategories = getMarketCategories4NotDeletAndLevel();
        wxGoodsListVO.setFilterCategoryList(marketCategories);


        //分页
        if (page == null || limit == null) {
            MarketGoodsExample goodsExample = new MarketGoodsExample();
            goodsExample.createCriteria().andCategoryIdEqualTo(categoryId).andDeletedEqualTo(false);
            List<MarketGoods> list = marketGoodsMapper.selectByExample(goodsExample);
            wxGoodsListVO.setList(list);
            wxGoodsListVO.setTotal(list.size());
        }
        PageHelper.startPage(page, limit);
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andCategoryIdEqualTo(categoryId).andDeletedEqualTo(false);
        List<MarketGoods> list = marketGoodsMapper.selectByExample(goodsExample);
        wxGoodsListVO.setTotal(list.size());

        //todo
        wxGoodsListVO.setLimit(limit);
        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(list);
        int pageNum = marketGoodsPageInfo.getPageNum();
        wxGoodsListVO.setPages(pageNum);

        List<MarketGoods> list1 = marketGoodsPageInfo.getList();
        wxGoodsListVO.setList(list1);
        wxGoodsListVO.setPage(marketGoodsPageInfo.getPageNum());






        return BaseRespVo.ok(wxGoodsListVO);
    }

    private List<MarketCategory> getMarketCategories4NotDeletAndLevel() {
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        categoryExample.createCriteria().andDeletedEqualTo(false).andLevelEqualTo("L2");
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(categoryExample);
        return marketCategories;
    }

    @Override
    public BaseRespVo getWxGoodsDetail(Integer id) {
        WxDetailVO wxDetailVO = new WxDetailVO();
        //info根据传入id查物品表获取信息
        MarketGoods info = getGoodsInfoById(id);

        wxDetailVO.setInfo(info);
        //productList;//根据传入id作为goods_id查寻market_goods_product
        List<MarketGoodsProduct> productList= getProductListByGoodsId(id);
        wxDetailVO.setProductList(productList);
        //brand;//根据brandId（来自MarketGoods info）查market_brands
        Integer brandId = info.getBrandId();
        MarketBrand brand = getMarketBrandByBrandId(brandId);
        wxDetailVO.setBrand(brand);
        //attribute;//是个数组Goodsid获取market_goods_attribute
        List<MarketGoodsAttribute> attribute = getGoodsAttributeByGoodsId(id);
        wxDetailVO.setAttribute(attribute);
        //根据info中的share是否为空来走
        //share;
        if (!info.getShareUrl().equals("")&&info.getShareUrl()!=null) {
            wxDetailVO.setShare(true);
            wxDetailVO.setShareImage(info.getShareUrl());
        }
        //根据info中的share为空
        //shareImage;//根据info中的share是否为空来走

        wxDetailVO.setShare(false);
        wxDetailVO.setShareImage("");

        //comment;//传入id为物品id查询comment表type为0
        WxDetailVO.CommentDTO commentDTO = new WxDetailVO.CommentDTO();
        List<MarketComment> commentListByGoodId = getCommentListByGoodId(id);
//        ArrayList<String> data = new ArrayList<>();
//        for (MarketComment marketComment : commentListByGoodId) {
//            data.add(marketComment.getContent());
//        }
        PageHelper pageHelper = new PageHelper();

        commentDTO.setData(commentListByGoodId);

        commentDTO.setCount(commentListByGoodId.size());
        wxDetailVO.setComment(commentDTO);

        //userHasCollect;//根具Userid来查看是否有收藏
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();


        if (principals!=null) {
            Object user= principals.getPrimaryPrincipal();
            MarketUser admin= (MarketUser) user;

            Integer userId = admin.getId();
            MarketCollectExample marketCollectExample = new MarketCollectExample();
            marketCollectExample.createCriteria().andDeletedEqualTo(false).andTypeEqualTo((byte) 0).andUserIdEqualTo(userId);
            Long l = marketCollectMapper.countByExample(marketCollectExample);
            wxDetailVO.setUserHasCollect(l.intValue());

        }
            wxDetailVO.setUserHasCollect(0);
        //issue;//整个issue表没有被逻辑删除的
        List<MarketIssue> issue = getIssueList4NoDelet();
        wxDetailVO.setIssue(issue);
        //groupon;//查看开团规则通过商品id
        List<MarketGrouponRules> groupRulersList = getGroupRulersList(id);
        wxDetailVO.setGroupon(groupRulersList);

        //获取specificationList

        List<WxDetailVO.SpecificationListDTO> specificationList = new ArrayList<>();
        List<MarketGoodsSpecification> specificationList4NotDeletByGoodId = getSpecificationList4NotDeletByGoodId(id);
        for (MarketGoodsSpecification marketGoodsSpecification : specificationList4NotDeletByGoodId) {
            WxDetailVO.SpecificationListDTO specificationListDTO = new WxDetailVO.SpecificationListDTO();

            specificationListDTO.setName(marketGoodsSpecification.getSpecification());

            List<MarketGoodsSpecification> collect = specificationList4NotDeletByGoodId.stream().filter(d -> d.getSpecification().equals(marketGoodsSpecification.getSpecification())).collect(Collectors.toList());
            specificationListDTO.setValueList(collect);
            specificationList.add(specificationListDTO);

        }
         wxDetailVO.setSpecificationList(specificationList);


//        1先查一下历史足迹里面是不是有这个goods_id
//          有 ->update
//          无 ->add+update

        if (principals!=null) {
            Object user= principals.getPrimaryPrincipal();
            MarketUser admin = (MarketUser) user;


            MarketFootprintExample example = new MarketFootprintExample();
            MarketFootprintExample.Criteria criteria = example.createCriteria();
            criteria.andDeletedEqualTo(false);
            criteria.andGoodsIdEqualTo(id);
            criteria.andUserIdEqualTo(admin.getId());

            List<MarketFootprint> footprints = footprintMapper.selectByExample(example);
            MarketFootprint marketFootprint = new MarketFootprint();
            if (footprints.size() == 0) {
                marketFootprint.setDeleted(false);
                marketFootprint.setUpdateTime(new Date());
                marketFootprint.setAddTime(new Date());
                marketFootprint.setUserId(admin.getId());
                marketFootprint.setGoodsId(id);
                footprintMapper.insertSelective(marketFootprint);
            } else {
                marketFootprint = footprints.get(0);
                marketFootprint.setUpdateTime(new Date());
                footprintMapper.updateByPrimaryKey(marketFootprint);
            }
        }
        return BaseRespVo.ok(wxDetailVO);
    }

    private  List<MarketGoodsSpecification> getSpecificationList4NotDeletByGoodId(Integer id) {
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        marketGoodsSpecificationExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(id);
       return marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);
    }

    private List<MarketGrouponRules> getGroupRulersList(Integer id) {
        MarketGrouponRulesExample marketGrouponRulesExample = new MarketGrouponRulesExample();
        marketGrouponRulesExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(id);
        return marketGrouponRulesMapper.selectByExample(marketGrouponRulesExample);
    }

    private List<MarketIssue> getIssueList4NoDelet() {
        MarketIssueExample marketIssueExample = new MarketIssueExample();
        marketIssueExample.createCriteria().andDeletedEqualTo(false);
        return marketIssueMapper.selectByExample(marketIssueExample);
    }

    private List<MarketComment> getCommentListByGoodId(Integer id) {
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        marketCommentExample.createCriteria().andDeletedEqualTo(false).andValueIdEqualTo(id).andTypeEqualTo((byte) 0);
        return marketCommentMapper.selectByExample(marketCommentExample);
    }

    private List<MarketGoodsAttribute> getGoodsAttributeByGoodsId(Integer id) {
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        marketGoodsAttributeExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(id);
       return marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);
    }

    private MarketBrand getMarketBrandByBrandId(Integer brandId) {
        return marketBrandMapper.selectByPrimaryKey(brandId);
    }

    private  List<MarketGoodsProduct> getProductListByGoodsId(Integer id) {
        List<MarketGoodsProduct> productList;
        MarketGoodsProductExample example = new MarketGoodsProductExample();
        example.createCriteria().andGoodsIdEqualTo(id);
        return marketGoodsProductMapper.selectByExample(example);
    }

    private MarketGoods getGoodsInfoById(Integer id) {
        return marketGoodsMapper.selectByPrimaryKey(id);
    }

    @Override
    public BaseRespVo getWxGoodsRelated(Integer id) {
        WxRelatedVO wxRelatedVO = new WxRelatedVO();
        //通过传入id查物品获取到类目id
        MarketGoods goodsInfoById = getGoodsInfoById(id);
        Integer categoryId = goodsInfoById.getCategoryId();
        //根据类目id查询列表获得list
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andDeletedEqualTo(false).andCategoryIdEqualTo(categoryId);
        List<MarketGoods> list = marketGoodsMapper.selectByExample(goodsExample);
//todo
        wxRelatedVO.setLimit(6);
        PageHelper.startPage(list.size(), 6);
        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(list);
        wxRelatedVO.setList(marketGoodsPageInfo.getList());
        wxRelatedVO.setPages(marketGoodsPageInfo.getPages());
        wxRelatedVO.setPage(marketGoodsPageInfo.getPageNum());
        wxRelatedVO.setTotal(list.size());
        //往历史足迹表中插入数据


        return BaseRespVo.ok(wxRelatedVO);
    }

    @Override
    public BaseRespVo getGoodsListByBrandId(WxGoodsListBO wxGoodsListBO) {
        WxGoodsListVO wxGoodsListVO = new WxGoodsListVO();
        Integer brandId = wxGoodsListBO.getBrandId();
        Integer page = wxGoodsListBO.getPage();
        Integer limit = wxGoodsListBO.getLimit();

        List<MarketCategory> marketCategories = getMarketCategories4NotDeletAndLevel();
        wxGoodsListVO.setFilterCategoryList(marketCategories);

        if (page == null || limit == null) {
            List<MarketGoods> list = getGoodsList4NotDelet4BrandId(brandId);
            wxGoodsListVO.setList(list);
            wxGoodsListVO.setTotal(list.size());
        }

        PageHelper.startPage(page, limit);
        List<MarketGoods> list = getGoodsList4NotDelet4BrandId(brandId);
        wxGoodsListVO.setTotal(list.size());

//todo
        wxGoodsListVO.setLimit(limit);
        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(list);
        int pageNum = marketGoodsPageInfo.getPageNum();
        wxGoodsListVO.setPages(pageNum);

        List<MarketGoods> list1 = marketGoodsPageInfo.getList();
        wxGoodsListVO.setList(list1);
        wxGoodsListVO.setPage(marketGoodsPageInfo.getPageNum());


        return BaseRespVo.ok(wxGoodsListVO);
    }

    private List<MarketGoods> getGoodsList4NotDelet4BrandId(Integer brandId) {
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andBrandIdEqualTo(brandId).andDeletedEqualTo(false);
        List<MarketGoods> list = marketGoodsMapper.selectByExample(goodsExample);
        return list;
    }
}
